using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Microsoft.UI.Xaml.Documents;
using System.Text.RegularExpressions;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI;
using DevCangjie.utils.Settings;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace DevCangjie.Pages.ConsolePage
{
    public sealed partial class OutputPage : Page
    {
        private static readonly Regex AnsiRegex = new Regex(@"\x1B\[(?<code>\d+)m", RegexOptions.Compiled);
        public OutputPage()
        {
            this.InitializeComponent();

            OutputTextBox.FontFamily = utils.Settings.Settings.Instance.ConsoleFont;
            OutputTextBox.FontSize = utils.Settings.Settings.Instance.ConsoleSize;
        }

        public void RefreshUI()
        {
            OutputTextBox.FontFamily = utils.Settings.Settings.Instance.ConsoleFont;
            OutputTextBox.FontSize = utils.Settings.Settings.Instance.ConsoleSize;
        }

        private IEnumerable<Run> ParseAnsi(string text)
        {
            int lastIndex = 0;
            MatchCollection matches = AnsiRegex.Matches(text);

            // 默认颜色
            Brush currentBrush = new SolidColorBrush(Settings.Instance.DefaultTextColor);

            foreach (Match match in matches)
            {
                // 添加匹配前的文本
                if (match.Index > lastIndex)
                {
                    string segment = text.Substring(lastIndex, match.Index - lastIndex);
                    yield return new Run
                    {
                        Text = segment,
                        Foreground = currentBrush,
                    };
                }

                // 解析 ANSI 代码
                if (int.TryParse(match.Groups["code"].Value, out int code))
                {
                    switch (code)
                    {
                        case 30:
                            currentBrush = new SolidColorBrush(Colors.Black);
                            break;
                        case 31:
                            currentBrush = new SolidColorBrush(Colors.Red);
                            break;
                        case 32:
                            currentBrush = new SolidColorBrush(Colors.Green);
                            break;
                        case 33:
                            currentBrush = new SolidColorBrush(Colors.Yellow);
                            break;
                        case 34:
                            currentBrush = new SolidColorBrush(Colors.Blue);
                            break;
                        case 35:
                            currentBrush = new SolidColorBrush(Colors.Magenta);
                            break;
                        case 36:
                            currentBrush = new SolidColorBrush(Colors.Cyan);
                            break;
                        case 37:
                            currentBrush = new SolidColorBrush(Colors.White);
                            break;
                        case 0:
                            // 重置颜色
                            currentBrush = new SolidColorBrush(Settings.Instance.DefaultTextColor);
                            break;
                        // 可以根据需求添加更多的 ANSI 转义代码
                        default:
                            break;
                    }
                }

                lastIndex = match.Index + match.Length;
            }

            // 添加剩余的文本
            if (lastIndex < text.Length)
            {
                string remaining = text.Substring(lastIndex);
                yield return new Run
                {
                    Text = remaining,
                    Foreground = currentBrush,
                };
            }
        }

        public void AppendOutput(string text)
        {
            DispatcherQueue.TryEnqueue(() =>
            {
                // 创建一个新的 Paragraph，如果不存在则创建
                Paragraph paragraph;
                if (OutputTextBox.Blocks.FirstOrDefault() is Paragraph existingParagraph)
                {
                    paragraph = existingParagraph;
                }
                else
                {
                    paragraph = new Paragraph();
                    OutputTextBox.Blocks.Add(paragraph);
                }

                // 解析带有 ANSI 转义序列的文本并添加到 Paragraph 中
                foreach (var run in ParseAnsi(text))
                {
                    paragraph.Inlines.Add(run);
                }

                // 强制更新布局，确保 ScrollViewer 能获取到最新的内容尺寸
                OutputTextBox.UpdateLayout();
                OutputScrollViewer.UpdateLayout();

                // 滚动到文本末尾
                OutputScrollViewer.ChangeView(null, OutputScrollViewer.ExtentHeight, null, true);
            });
        }

    }
}

